package com.beney.util.db;

import com.beney.common.StorageInfo;
import com.beney.pojo.User;

import java.io.*;
import java.util.HashSet;
import java.util.Set;

/**
 * 读入文件工具
 *
 * @author Beney
 */
public class FileInUtil {
    private FileInUtil() {
    }

    /**
     * 获取用户生成过的所有题目的HashCode集合
     *
     * @param userName 用户名
     * @return hashcode集合
     */
    public static Set<Integer> readAllQuesCodeFromUser(String userName) {
        Set<Integer> codes = new HashSet<>();
        String dirPath = StorageInfo.PAPERS_DIR + '/' + userName;
        String content;
        File dir = new File(dirPath);
        try {
            if (dir.isDirectory()) {
                String[] fileList = dir.list();
                if (fileList != null) {
                    for (String filename : fileList) {
                        BufferedReader reader = new BufferedReader(new FileReader(dirPath + "\\" + filename));
                        while ((content = reader.readLine()) != null) {
                            if (content.length() > 2) {
                                // 获取每一个题目的hashcode
                                int it = content.indexOf(StorageInfo.QID_DEC);
                                codes.add(content.substring(it + 1).hashCode());
                            }
                        }
                    }
                }
            }
        } catch (FileNotFoundException e) {
            System.out.println(dirPath + " 之中，文件查找失败");
        } catch (IOException e) {
            System.out.println(dirPath + " 之中，文件读取出错");
        }
        return codes;
    }

    /**
     * 从存储文件中反序列化读取用户对象
     * 失败的时候会打印出相应的提示信息
     *
     * @param name 用户名
     * @param pwd 密码
     * @return 成功获取的用户对象；null-获取失败
     */
    public static User readUser(String name, String pwd) {
        User res = null;
        try {
            ObjectInputStream in = new ObjectInputStream(
                    new FileInputStream(StorageInfo.USER_DIR + "/" + name)
            );
            User u = (User) in.readObject();
            if (u.getPwd().equals(pwd)) { // 密码也需要匹配
                res = u;
            }
        } catch (IOException | ClassNotFoundException ignored) {
        }
        return res;
    }
}
